use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let create = manager
            .create_table(
                Table::create().table(User::Table).if_not_exists()
                .col( ColumnDef::new(User::Id).integer().not_null().auto_increment().primary_key().comment("id") )
                .col( ColumnDef::new(User::Username).string_len(8).not_null().unique_key().comment("用户名") )
                .col( ColumnDef::new(User::Name).string_len(8).comment("真实姓名") )
                .col( ColumnDef::new(User::Phone).char_len(11).not_null().unique_key().comment("手机号码") )
                .col( ColumnDef::new(User::Password).char_len(32).not_null().comment("密码") )
                .col( ColumnDef::new(User::Type).integer().comment("用户类型") )
                .col( ColumnDef::new(User::Head).string_len(50).comment("头像") )
                .col( ColumnDef::new(User::ExpireTime).date().comment("到期时间") )
                .col( ColumnDef::new(User::Role).tiny_integer().not_null().comment("角色") )
                .col( ColumnDef::new(User::Perm).json().comment("权限") )
                .col( ColumnDef::new(User::Disabled).boolean().not_null().default(false).comment("禁用") )
                .col( ColumnDef::new(User::Mark).string_len(30).comment("备注") )
                .col( ColumnDef::new(User::CreateUser).integer().not_null().comment("创建人") )
                .col( ColumnDef::new(User::UpdateUser).integer().comment("修改人") )
                .col( ColumnDef::new(User::CreateTime).timestamp().default(Expr::current_timestamp()).comment("创建时间") )
                .col( ColumnDef::new(User::UpdateTime).timestamp().default(Expr::current_timestamp()).extra("on update current_timestamp").comment("更新时间") )
                .to_owned()
            ).await;
        match create {
            Ok(_f) => {
                let db = manager.get_connection();
                let insert = db.execute_unprepared(
                    "insert into user(name, username, password, phone, disabled, create_user, role) values('管理员', 'admin', md5('a123456'), '', false, 1, 0)"
                ).await;
                match insert {
                    Ok(_f) => Ok(()),
                    Err(e) => Err(e)
                }
            },
            Err(e) => Err(e)
        }
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager.drop_table(Table::drop().table(User::Table).to_owned()).await
    }
}

#[derive(DeriveIden)]
enum User {
    Table,
    Id,
    Username,
    Name,
    Phone,
    Type,
    Head,
    ExpireTime,
    Role,
    Perm,
    Disabled,
    Mark,
    CreateUser,
    UpdateUser,
    CreateTime,
    UpdateTime,
    Password
}